package ru.mirent.entity.listeners.allure;

import io.qameta.allure.Allure;
import io.qameta.allure.listener.TestLifecycleListener;
import io.qameta.allure.model.Attachment;
import io.qameta.allure.model.Status;
import io.qameta.allure.model.StatusDetails;
import io.qameta.allure.model.TestResult;
import ru.mirent.exceptions.CustomAssertionFailedError;

import java.util.List;
import java.util.Objects;

public class AllureTestLifecycleListener implements TestLifecycleListener {
    private static final ThreadLocal<Throwable> THROWABLE_THREAD_LOCAL = new ThreadLocal<>();

    public static ThreadLocal<Throwable> getThrowableThreadLocal() {
        return THROWABLE_THREAD_LOCAL;
    }

    public void beforeTestStop(TestResult result) {
        if (Allure.getLifecycle().getCurrentTestCase().isPresent()) {
            Throwable throwable = THROWABLE_THREAD_LOCAL.get();
            if (Objects.isNull(throwable)) {
                result.setStatus(Status.PASSED);
            } else {
                if (throwable instanceof CustomAssertionFailedError) {
                    result.setStatus(Status.FAILED);
                    CustomAssertionFailedError customAssertionFailedError =
                            (CustomAssertionFailedError) throwable;

                    // TODO Доработать вывод статуса
//                    result.setStatusDetails(
//                            new StatusDetails().
//                    );
//                    Allure.addAttachment("Вложение", "text/plain",
//                            customAssertionFailedError.getAttachment().toString(), ".txt");
//                } else if (throwable instanceof CustomRuntimeException) {
//                    result.setStatus(Status.BROKEN);
                } else {
                    result.setStatus(Status.BROKEN);
                }
            }
        }
    }
}
